package com.itobase.questionnaire.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itobase.questionnaire.VO.UnsubTeacher;
import com.itobase.questionnaire.exception.WrongParameterException;
import com.itobase.questionnaire.model.*;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.*;
import com.itobase.questionnaire.service.IOutcomeService;
import com.itobase.questionnaire.service.IResultService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.util.ListUtil;
import com.itobase.questionnaire.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.BinaryClient;

import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cong
 * @date 2018/7/31
 */

@Service
public class ResultService implements IResultService {

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    QuesnaireRepository quesnaireRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    IOutcomeService outcomeService;

    @Autowired
    SendListRepository sendListRepository;
    @Autowired
    SurveyGroupRepository surveyGroupRepository;


    private static final String sheetName = "满意度";

    private static final Integer colNum = 4;
    private static String[] colHeads = new String[]{"类型","姓名","部门","满意度"};
    private static final Integer teaQues = 2;
    private static final Integer stuQues = 3;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public JSONObject getResultPerson(String submitId) {
        JSONObject previewData = new JSONObject();
        Submission submission = Optional.ofNullable(submitRepository.findOne(submitId)).orElseThrow(()->new RuntimeException("答卷id错误"));
        Survey survey = Optional.ofNullable(surveyRepository.findOne(submission.getSurveyId())).orElseThrow(()->new RuntimeException("调查不存在"));
        Questionnaire questionnaire = Optional.ofNullable(quesnaireRepository.findOne(survey.getQuestionsID())).orElseThrow(()->new RuntimeException("调查绑定的问卷不存在"));
        List<Question> questions = questionnaire.getQuestionList();
        if(submission.getUserId()!=null){
            User user = userRepository.findOne(submission.getUserId());
            Boolean isTeacher= user.getUserTypeId().equals(Constant.TEACID);
            Question question;
            if(isTeacher){
                questions.remove(4);//移除熟悉程度那一题
                question = questions.get(stuQues);
                questions.remove(question);
                for(int i=3;i<questions.size();i++){
                    int oldNum = questions.get(i).getOrderNumber();
                    oldNum--;
                    questions.get(i).setOrderNumber(oldNum);
                }
            }else{
                question = questions.get(teaQues);
                questions.remove(question);
                for(int i=2;i<questions.size();i++){
                    int oldNum = questions.get(i).getOrderNumber();
                    oldNum--;
                    questions.get(i).setOrderNumber(oldNum);
                }
            }
        }
        Collections.sort(questions);

        Map<Integer, String> answer = submission.getAnswer();

        previewData.put("调查名称", survey.getTitle());

        previewData.put("section",Optional.ofNullable(survey.getSection()).orElseThrow(()->new RuntimeException("调查未绑定部门")));
        Map<Question, String> quesAndResult;
        int count = 1;
        for (Question e : questions) {
            quesAndResult = new HashMap<>();
            quesAndResult.put(e, answer.get(e.getOrderNumber()));
            previewData.put(String.valueOf(count), quesAndResult);
            count++;
        }
        return previewData;
    }

    @Override
    public Integer getRateExcel(String surveyId, HttpServletResponse response) {
        Survey survey = surveyRepository.findOne(surveyId);

        if(!StringUtil.isNotEmpty(survey.getContentRate())){
            survey.setContentRate(outcomeService.getSurveyContentRate(survey));
        }
        String excelTitle = survey.getTitle().concat(MessageFormat.format("(总满意度：{0})",survey.getContentRate()));
        List<Submission> submissionList = submitRepository.findBySurveyId(surveyId);

        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFCellStyle columnTopStyle = outcomeService.getColumnTopStyle(wb);//获取列头样式对象
        HSSFCellStyle dataStyle = outcomeService.getStyle(wb);

        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(30);
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cellTitle = row0.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, colNum-1));
        cellTitle.setCellValue(excelTitle);
        cellTitle.setCellStyle(columnTopStyle);

        HSSFRow rowHeadName = sheet.createRow(2);//第0行和第一行为标题
        /*
            创建表头
        */
        for (int n = 0; n < colNum; n++) {
            HSSFCell cellRowName = rowHeadName.createCell(n);
            cellRowName.setCellType(CellType.STRING);

            HSSFRichTextString text = new HSSFRichTextString(colHeads[n]);
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
        }
        List<User> userList = survey.getUserList();
        //将userList改造成map,方便获取user的信息
        Map<String,User> userMap = new HashMap<>();
        userList.forEach(user -> userMap.put(user.getId(),user));
        int rowIndex = 3;//前三行是标题和表头
        for (int i = 0; i < submissionList.size(); i++,rowIndex++) {

            Submission submission = submissionList.get(i);
            Map<String,String> outcome = submission.getOutcome();

            HSSFRow row = sheet.createRow(rowIndex);//前三行是标题和表头

            LinkedList<String> colData = new LinkedList<>();
            outcome.forEach((k,v)->{
                colData.add(k);
                colData.add(userMap.get(submission.getUserId()).getName());
                colData.add(userMap.get(submission.getUserId()).getCollegeName());
                colData.add(v);
            });

            int colIndex = 0;
            for (int col = 0; col < colData.size(); col++,colIndex++) {
                if(colIndex>=4){
                    rowIndex++;
                    row = sheet.createRow(rowIndex);
                    colIndex=0;
                }
                HSSFCell cell = row.createCell(colIndex, CellType.STRING);
                String value = colData.get(col);
                if(StringUtils.isEmpty(value)){
                    value = "";
                }
                cell.setCellValue(value);
                cell.setCellStyle(dataStyle);
            }
        }
        outcomeService.writeToResponse(response, wb,survey.getTitle().concat("结果分析"));
        return submissionList.size();
    }



    public Integer getResultExcel(HttpServletResponse response){
        Map<String,Map<String,Object>> result = getResult();

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle columnTopStyle = outcomeService.getColumnTopStyle(wb);//获取列头样式对象
        HSSFCellStyle dataStyle = outcomeService.getStyle(wb);


        String[] colHeads1 = new String[]{"部门","发放问卷","答题问卷","有效问卷","学生应答数","学生有效问卷","学生答题百分比","学生有效答题百分比","学生差的人数","教师应答数","教师答题数","教师答题百分比","教师差的人数","备注"};
        HSSFSheet sheet = wb.createSheet("测评结果统计");
        sheet.setDefaultColumnWidth(30);
        // 设置第一行
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cellTitle = row0.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 13));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        cellTitle.setCellValue(sdf.format(System.currentTimeMillis())+" 系统调查状态统计表");
        cellTitle.setCellStyle(columnTopStyle);

        HSSFRow rowHeadName = sheet.createRow(2);
        /*
            设置表头
         */
        for (int n = 0; n < 14; n++) {
            HSSFCell cellRowName = rowHeadName.createCell(n);
            cellRowName.setCellType(CellType.STRING);
            HSSFRichTextString text = new HSSFRichTextString(colHeads1[n]);
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
        }
        int rowLine = 3;
        for (Map.Entry<String,Map<String,Object>> entry : result.entrySet()){
            HSSFRow row = sheet.createRow(rowLine);

            for (int col = 0; col < 14; col++){
                HSSFCell cell = row.createCell(col,CellType.STRING);
                String value = "";
                if (col==0){
                     value = entry.getKey();
                }else{
                     value = String.valueOf(entry.getValue().get(colHeads1[col]));
                }
                cell.setCellValue(value);
                cell.setCellStyle(dataStyle);
            }
            rowLine++;
        }

        /*
        HSSFRow lastRow = sheet.createRow(rowLine);
        HSSFCell cell = lastRow.createCell(0,CellType.STRING);
        cell.setCellValue("总计");
        cell.setCellStyle(dataStyle);

        for (int col = 1 ; col < 7;col++){
            int sum = 0;
            HSSFCell cell1 = lastRow.createCell(col,CellType.STRING);
            for (Map.Entry<String,Map<String,Object>> entry : result.entrySet()){
                sum += entry.getValue().get(colHeads1[col-1]);
            }
            cell1.setCellValue(String.valueOf(sum));
            cell1.setCellStyle(dataStyle);
        }
        */
        for (int col = 0;col<14;col++)
            sheet.setColumnWidth(col, (int)((13 + 0.72) * 256));

        outcomeService.writeToResponse(response, wb,"测评统计");
        return null;
    }

    public void getUnsubTeacher(HttpServletResponse response,String surveyGroupId){
        List<UnsubTeacher> result = getUnsubTeacher(surveyGroupId);

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle columnTopStyle = outcomeService.getColumnTopStyle(wb);//获取列头样式对象
        HSSFCellStyle dataStyle = outcomeService.getStyle(wb);

        String[] colHeads1 = new String[]{"工号","姓名","手机号","学院","问卷","职位"};
        HSSFSheet sheet = wb.createSheet("测评结果统计");
        sheet.setDefaultColumnWidth(30);
        HSSFRow rowHeadName = sheet.createRow(0);
        /*
            设置表头
         */
        for (int n = 0; n < 6; n++) {
            HSSFCell cellRowName = rowHeadName.createCell(n);
            cellRowName.setCellType(CellType.STRING);

            HSSFRichTextString text = new HSSFRichTextString(colHeads1[n]);
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
        }
        int rowLine = 1;
        Map<String,List<UnsubTeacher>> map = result.stream().collect(Collectors.groupingBy(UnsubTeacher::getCollege));
        for (Map.Entry<String,List<UnsubTeacher>> entry :map.entrySet()) {
            for (UnsubTeacher unsubTeacher : entry.getValue()) {
                HSSFRow row = sheet.createRow(rowLine);

                HSSFCell cell1 = row.createCell(0);
                cell1.setCellValue(unsubTeacher.getUsername());
                cell1.setCellType(CellType.STRING);
                cell1.setCellStyle(dataStyle);

                HSSFCell cell2 = row.createCell(1);
                cell2.setCellValue(unsubTeacher.getName());
                cell2.setCellType(CellType.STRING);
                cell2.setCellStyle(dataStyle);

                HSSFCell cell3 = row.createCell(2);
                cell3.setCellValue(unsubTeacher.getPhone());
                cell3.setCellType(CellType.STRING);
                cell3.setCellStyle(dataStyle);

                HSSFCell college = row.createCell(3);
                college.setCellValue(entry.getKey());
                college.setCellType(CellType.STRING);
                college.setCellStyle(dataStyle);

                HSSFCell cell4 = row.createCell(4);
                cell4.setCellValue(unsubTeacher.getSurveyGroupName());
                cell4.setCellType(CellType.STRING);
                cell4.setCellStyle(dataStyle);

                HSSFCell cell5 = row.createCell(5);
                cell5.setCellValue(unsubTeacher.getGroup());
                cell5.setCellType(CellType.STRING);
                cell5.setCellStyle(dataStyle);

                rowLine++;
            }
        }

        outcomeService.writeToResponse(response, wb,"未提交老师");
    }




    public static Map combine(Map map1, Map map2) {
        Object[] value1 = null;
        Object[] value2 = null;
        Set set = map1.keySet();
        Iterator iterator = set.iterator();
        Object key = null;
        List list = null;
        for (int index = 0; index < set.size(); index++) {
            key = iterator.next();
            Object valueTemp1 = map1.get(key);
            Object valueTemp2 = map2.get(key);
            if (null == valueTemp1 || null == valueTemp2) {
                continue;
            }
            value1 = ((List) valueTemp1).toArray();
            value2 = ((List) valueTemp2).toArray();
            Object[] value = new Object[value1.length + value2.length];
            System.arraycopy(value1, 0, value, 0, value1.length);
            System.arraycopy(value2, 0, value, value1.length, value2.length);
            list = (List) Arrays.asList(value);
            map1.put(key, list);
        }
        return map1;
    }


    public Map<String,Map<String,Object>> getResult() {
        List<Submission> submissionList = submitRepository.findAll();
        Map<String,Map<String,Object>> result = new HashMap<>();
        //部门   发放问卷   答题问卷   有效问卷    教师答题数   学生答题数
        //Map<String,List<Submission>>
        for (Map.Entry<String, List<Submission>> entry : submissionList.stream().collect(Collectors.groupingBy(Submission::getSurveyId)).entrySet()) {//拿到提交数量
            int teaSubCount = 0;
            int stuSubCount = 0;
            int available = 0;
            int teaCount = 0;
            int stuCount = 0;
            Map<String, Object> surveyResult = new HashMap<>();
            Survey survey = surveyRepository.findById(entry.getKey());
            for (Submission submission : entry.getValue()) {
                User user = Optional.ofNullable(userRepository.findOne(submission.getUserId()))
                        .orElseThrow(() -> new WrongParameterException("找不到该用户" + "--" + submission.getId()));
                if (user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID)
                        || user.getUserTypeId().equals(Constant.STUID)) {
                    stuSubCount++;
                    Map<String, String> map = submission.getOutcome();
                    for (Map.Entry<String,String> e : map.entrySet()){
                        if (Double.parseDouble(e.getValue())>0){
                            available++;
                            continue;
                        }
                    }
                } else if (user.getUserTypeId().equals(Constant.TEACID)) {
                    teaSubCount++;
                } else {
                    throw new WrongParameterException("出错了" + submission.getId());
                }
            }
            List<User> userList = survey.getUserList();
            for (User user : userList)
            {
                if (user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID)
                        || user.getUserTypeId().equals(Constant.STUID)) {
                    stuCount++;
                }else if (user.getUserTypeId().equals(Constant.TEACID)) {
                    teaCount++;
                }else{
                    throw new WrongParameterException("出错了" + user.getId());
                }
            }

            stuCount=stuCount-2;
            surveyResult.put("发放问卷",userList.size());
            surveyResult.put("答题问卷",stuSubCount+teaSubCount);
            surveyResult.put("有效问卷",available+teaSubCount);
            if (stuCount>0) {
                surveyResult.put("学生应答数",stuCount);
                surveyResult.put("学生有效问卷", available);
                if (stuCount>360)
                    stuCount=360;
                surveyResult.put("学生答题百分比", getPersent(stuSubCount,stuCount));
                surveyResult.put("学生有效答题百分比", getPersent(available,stuCount));
                long needCount = Math.round(Math.ceil(stuCount*0.2-available));
                if (needCount>0) {
                    surveyResult.put("学生差的人数", needCount);
                }else {
                    surveyResult.put("学生差的人数", 0);
                }
            }else{
                surveyResult.put("学生应答数","");
                surveyResult.put("学生有效问卷", "");
                surveyResult.put("学生答题百分比", "");
                surveyResult.put("学生有效答题百分比", "");
                surveyResult.put("学生差的人数","");
            }
            surveyResult.put("教师应答数",teaCount);
            surveyResult.put("教师答题数", teaSubCount);
            surveyResult.put("教师答题百分比",getPersent(teaSubCount,teaCount));
            long needCount = Math.round(Math.ceil(teaCount*0.6-teaSubCount));
            if (needCount>0) {
                surveyResult.put("教师差的人数", needCount);
            }else{
                surveyResult.put("教师差的人数", 0);
            }
            surveyResult.put("备注","");

            result.put(surveyGroupRepository.findOne(survey.getSurveyGroupId()).getGroupName(),surveyResult);
        }
        return result;
    }

    public List<UnsubTeacher> getUnsubTeacher(){
        List<SurveyGroup> surveyGroupList = surveyGroupRepository.findAll();
        List<UnsubTeacher> result = new ArrayList<>();
        Set<String> set = new HashSet<>();
        surveyGroupList.forEach(surveyGroup -> {
            Map<String,List<String>> temp = surveyGroup.getGroup();
            temp.forEach((k,v)->{
                v.forEach(id->{
                    List<Submission> submissionList = submitRepository.findByUserId(id);
                    //未提交
                    if (submissionList==null || submissionList.size()==0){
                        User user = userRepository.findOne(id);
                        if(user.getUserTypeId().equals(Constant.TEACID)) {
                            UnsubTeacher teacher = new UnsubTeacher();
                            teacher.setName(user.getName());
                            teacher.setPhone(user.getLongPhone());
                            teacher.setUsername(user.getUsername());
                            teacher.setSurveyGroupName(surveyGroup.getGroupName());
                            teacher.setGroup(k);
                            teacher.setCollege(user.getCollegeName());
                            if (set.add(user.getUsername()))
                                 result.add(teacher);
                        }
                    }
                });
            });
        });

        return result;
    }

    public List<UnsubTeacher> getUnsubTeacher(String surveyGoupId){
        SurveyGroup surveyGroup = surveyGroupRepository.findOne(surveyGoupId);
        List<UnsubTeacher> result = new ArrayList<>();
        Set<String> set = new HashSet<>();
            Map<String,List<String>> temp = surveyGroup.getGroup();
            temp.forEach((k,v)->{
                v.forEach(id->{
                    List<Submission> submissionList = submitRepository.findByUserId(id);
                    //未提交
                    if (submissionList==null || submissionList.size()==0){
                        User user = userRepository.findOne(id);
                        if(user.getUserTypeId().equals(Constant.TEACID)) {
                            UnsubTeacher teacher = new UnsubTeacher();
                            teacher.setName(user.getName());
                            teacher.setPhone(user.getLongPhone());
                            teacher.setUsername(user.getUsername());
                            teacher.setSurveyGroupName(surveyGroup.getGroupName());
                            teacher.setGroup(k);
                            teacher.setCollege(user.getCollegeName());
                            if (set.add(user.getUsername()))
                                result.add(teacher);
                        }
                    }
                });
            });


        return result;
    }


    private String getPersent(int num1,int num2){
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMaximumFractionDigits(2);
        return format.format((float)num1/(float)num2);
    }

}
